513. 找树左下角的值
为保证权益,题目请参考 513. 找树左下角的值(From LeetCode).
解决方案1
Python
python
# 513. 找树左下角的值
# https://leetcode.cn/problems/find-bottom-left-tree-value/
from typing import Optional, Tuple
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> Tuple[int, int]:
if root:
lv, ld = dfs(root.left)
rv, rd = dfs(root.right)
if ld == 0:
if rd == 0:
return root.val, 1
else:
return rv, rd + 1
else:
if rd == 0:
return lv, ld + 1
else:
if ld >= rd:
return lv, ld + 1
else:
return rv, rd + 1
else:
return -1, 0
rv, rd = dfs(root)
return rv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41